let server = require("express")();
const { response } = require("express");
let expressStatic = require("express-static");
const { request } = require("http");
let mysql = require("mysql")
const port = 8080;

let sql = mysql.createConnection({
	host     : 'localhost',
	user     : 'root',
	password : '123456',
	database : 'sms',
	timezone : "08:00"
});
sql.connect();
//前端发送ajax后端返回的数据,重前端写法,前端枚举插入到内容
server.get("/getstudentList",(request,response)=>{
    sql.query(`select * from students`,(error,data)=>{
        if(error){
            console.log(error)
            response.send("error")
        }else{
            //前端不能直接返回json对象的
            //为什么我这里的data和面转成JSon字符串的值一样没有报错呢?
          response.send(data)//object
             //response.send(JSON.stringify(data));//string
        }
    })
})

//删除
server.get("/deleteStudent",(request,response)=>{
    //${request.query.id}前端发送的id值
    //下面是删除数据中的数据一行
    sql.query(`delete from students where id=${request.query.id}`,(error,data)=>{
        if(error){
            console.log(error)//输出到nodejs中
            response.send("error")
        }else{
            response.send("success");
          console.log(`${request.query.id}`)  
        }
    })
})

//弹出层
//request:包含前端发送的参数
//response:包含后端返回的参数
server.get("/addStudent",(request,response)=>{
    let p = request.query;
    sql.query(`INSERT INTO students (name,age,sex,city,joinDate) VALUES ("${p.name}","${p.age}","${p.sex}","${p.city}","${p.joinDate}")`,(error,data)=>{
        if(error){
			console.log(error)
			response.send("error")
		}
		else{
			response.send("success")
			console.log(`新增学生${p.name}操作成功`)
		}
    })
})




//测试库
// server.get("/",(request,response)=>{
//     sql.query(`select * from students`,(error,data)=>{
//         if(error){
//             console.log(error)
//             response.send("error")
//         }else{
//             //前端不能直接返回json对象的
//             //为什么我这里的data和面转成JSon字符串的值一样没有报错呢?
//             response.send(data)//object
//             // response.send(JSON.stringify(data));//string
//         }
//     })
// })

// server.get("/",(request,response)=>{
//     response.send("hello")
// })











server.use(expressStatic(__dirname + '/liuqiang'))

server.listen(port);
console.log(`server is running at ${port}`)